package com.oh.core.server.initializer;

import com.oh.core.common.codec.OhDecoder;
import com.oh.core.common.codec.OhEncoder;
import com.oh.core.server.handler.OhServerHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class OhServerInitializer extends ChannelInitializer<SocketChannel> {

    @Resource
    OhEncoder ohEncoder;

    @Resource
    OhServerHandler ohServerHandler;

    @Value("${oh.heartBeat.readerIdleTime:300}")
    private long readerIdleTime;

    @Value("${oh.heartBeat.writerIdleTime:0}")
    private long writerIdleTime;

    @Value("${oh.heartBeat.allIdleTime:0}")
    private long allIdleTime;

    ChannelHandler [] lastHandlers;

    public void setLastHandlers(ChannelHandler[] lastHandlers) {
        this.lastHandlers = lastHandlers;
    }
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //用户每次请求都会从第一个Handler开始
        //设置超时时间（心跳）
        pipeline.addLast(new IdleStateHandler(readerIdleTime, writerIdleTime, allIdleTime, TimeUnit.SECONDS));
        // 消息解码: 截取消息体，消息头和消息体 第3个参数（长度）从第5个byte开始，4个报文长度
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 5, 4, 0, 0));
        // 添加对byte数组的编解码，netty提供了很多编解码器，你们可以根据需要选择
        pipeline.addLast(ohEncoder);
        pipeline.addLast(new OhDecoder(Integer.MAX_VALUE, 5, 4, 0, 0, false));

        // 添加上自己的处理器
        pipeline.addLast(ohServerHandler);
        // 其他处置类
        if(lastHandlers != null && lastHandlers.length > 0){
            pipeline.addLast(lastHandlers);
        }
    }
}
